//
// Copyright (c) 2005 BroadVision, Inc. All rights reserved.
//
// This software is copyrighted.  Under the copyright laws, this software
// may not be copied, in whole or in part, without prior written consent
// of BroadVision, Inc. or its assignees.  This software is provided under
// the terms of a license between BroadVision and the recipient, and its
// use is subject to the terms of that license.
//
// This software may be protected by one or more U.S. and International
// patents.  Certain applications of BroadVision One-To-One software are
// covered by U.S. patent 5,710,887.
//
// TRADEMARKS: BroadVision and BroadVision One-To-One are registered
// trademarks of BroadVision, Inc., in the United States and the European
// Community, and are trademarks of BroadVision, Inc., in other
// countries.  The BroadVision logo, is a trademark of BroadVision, Inc.,
// in the United States and other countries. Additionally, IONA and Orbix
// are trademarks of IONA Technologies, Ltd.  RSA, MD5, and RC2 are
// trademarks of RSA Data Security, Inc.
//

package com.broadvision.manage.common.tools.action.group;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
import org.apache.struts.Globals;

import com.broadvision.system.accesscontrol.client.*;
import com.broadvision.system.accesscontrol.exceptions.AccessControlException;
import com.broadvision.visitor.client.VisitorManager;
import com.broadvision.visitor.client.Visitor;
import com.broadvision.visitor.client.VisitorGroupManager;
import com.broadvision.visitor.exceptions.VisitorGroupException;
import com.broadvision.visitor.interfaces.VisitorGroup;
import com.broadvision.web.util.ViewDynaBean;
import com.broadvision.portal.services.OrganizationObjectInfo;

import com.broadvision.manage.tools.action.BaseAction;
import com.broadvision.manage.common.tools.action.user.UserUtils;
import com.broadvision.manage.common.tools.user.UserProfile;

/**
 * View a group's parents' administrators
 */
public class GroupParentAdministratorsViewAction extends BaseAction {

  public static final String VIEW_BEAN_NAME = "mtGroupAdministratorsView";
  public static final String DTO_BEAN_NAME  = "mtGroupAdministratorDTO";

  public static final VisitorManager visitorMgr = new VisitorManager();

  /**
   * Implements the action for viewinga group's parents' administrators
   * <p> <p>
   * @param mapping <code>ActionMapping</code> object used to select this instance
   * @param form Optional <code>ActionForm</code> bean for this request (if any)
   * @param request <code>HttpServletRequest</code> object to process
   * @param response <code>HttpServletResponse</code> object to process
   * <p> <p>
   * @return <code>ActionForward</code> instance describing where and how
   * control should be forwarded, or null if the response has already been completed
   * <p> <p>
   * @throws Exception if an error occurs
   */
  public ActionForward processExecute(ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
  throws Exception
  {
    try {
      ViewDynaBean view = new ViewDynaBean(VIEW_BEAN_NAME, mapping);
      request.setAttribute(VIEW_BEAN_NAME, view);
      String originalGroupFQN = (String)UserUtils.getP(form, "originalGroupFQN");
      if (originalGroupFQN != null && originalGroupFQN.length() > 0) {
        VisitorGroup thisGroup = VisitorGroupManager.getVisitorGroupByFqn(originalGroupFQN);
        String groupFriendlyName = thisGroup.getFriendlyName();
        int index = groupFriendlyName.lastIndexOf("/");
        if (index > -1) {
          PropertyUtils.setSimpleProperty(view, "name", groupFriendlyName.substring(index + 1));
        }
        else {
          PropertyUtils.setSimpleProperty(view, "name", groupFriendlyName);
        }
      }
      else {
        PropertyUtils.setSimpleProperty(view, "name", "");
      }
      String groupFQN = (String)UserUtils.getP(form, "groupFQN");
      VisitorGroup parentGroup = VisitorGroupManager.getVisitorGroupByFqn(groupFQN);
      HashMap adminMap = this.getParentAdministerators(parentGroup);
      Iterator adminIterator = adminMap.values().iterator();
      MessageResources resources = getResources(request, "mt.messages");
      Locale locale = getLocale(request);
      List list = new ArrayList();
      for (int i = 0; i < adminMap.size() && adminIterator.hasNext(); i++) {
        Visitor visitor = (Visitor)adminIterator.next();
        ViewDynaBean dto = new ViewDynaBean(DTO_BEAN_NAME, mapping);
        PropertyUtils.setSimpleProperty(dto, "signinId", visitor.getUserAlias());
        String name = UserUtils.getFormattedVisitorFullName(visitor, resources, locale, "fullNameOnly");
        PropertyUtils.setSimpleProperty(dto, "name", name);
        list.add(dto);
      }
      PropertyUtils.setSimpleProperty(view, "users", list);
    }
    catch (Exception ex) {
      ex.printStackTrace();
      request.setAttribute(Globals.ERROR_KEY, "error.application");
      return mapping.findForward("failure");
    }
    return mapping.findForward("success");
  }
  
  protected HashMap getParentAdministerators(VisitorGroup thisGroup) {
    HashMap adminMap = new HashMap();
    AccessManager aclMgr = null;
    List parentGroupList = null;
    try {
      parentGroupList = thisGroup.getParents(true);
      aclMgr = AccessManager.instance();
    }
    catch (VisitorGroupException ex) {
      ;
    }
    catch (AccessControlException ex) {
      ;
    }
    if (thisGroup != null) {
      parentGroupList.add(thisGroup);
    }
    if (parentGroupList != null && parentGroupList.isEmpty() == false) {
      for (int i = parentGroupList.size() - 1; i >= 0; i--) {
        VisitorGroup oneVisitorGroup = (VisitorGroup)parentGroupList.get(i);
        OrganizationObjectInfo oneOrgOI = new OrganizationObjectInfo(oneVisitorGroup);
        ArrayList oneOrgOIAdmins = null;
        try {
          oneOrgOIAdmins = (ArrayList)aclMgr.getPrincipalsInRole(UserProfile.ORGANIZATION_ADMIN, oneOrgOI);
        }
        catch (AccessControlException ex) {
          ;
        }
        if (oneOrgOIAdmins != null && oneOrgOIAdmins.isEmpty() == false) {
          for (int j = 0; j < oneOrgOIAdmins.size(); j++) {
            Visitor oneVisitor = (Visitor)oneOrgOIAdmins.get(j);
            adminMap.put(oneVisitor.getName(), oneVisitor); 
          }
        }
      }
    }
    return adminMap;
  }

}
